package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.dao.jdbc.StudentExchangeDetailsJdbc;
import com.wuseguang.springcloud.dao.repository.PrizeRepository;
import com.wuseguang.springcloud.dao.repository.StudentExchangeDetailsRepository;
import com.wuseguang.springcloud.dao.repository.StudentExchangeRecordRepository;
import com.wuseguang.springcloud.entity.Prize;
import com.wuseguang.springcloud.entity.StudentExchangeDetails;
import com.wuseguang.springcloud.entity.StudentExchangeRecord;
import com.wuseguang.springcloud.service.StudentExchangeDetailsService;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生积分信息以及兑换详情表 服务实现类
 * </p>
 *
 * @author 
 * @since 2020-06-19
 */
@Service
public class StudentExchangeDetailsServiceImpl implements StudentExchangeDetailsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private StudentExchangeDetailsJdbc studentExchangeDetailsJdbc;
    @Autowired
    private StudentExchangeDetailsRepository studentExchangeDetailsRepository;
    @Autowired
    private PrizeRepository prizeRepository;
    @Autowired
    private StudentExchangeRecordRepository studentExchangeRecordRepository;

    @Override
    public Result findStudentExchangeDetails(String deviceid, String studentId) {
        logger.info("学生积分信息以及兑换详情");
        Map<String, Object> stringObjectMap4 = studentExchangeDetailsJdbc.queryDevice(deviceid);

        //查询学生的兑换详情
        String sql = "select if(sed.fraction is null,0,sed.fraction) fraction,s.id student_id, " +
                "if(sed.prize_number is null,0,sed.prize_number) prize_number," +
                "if(sed.redeemed_points is null,0,sed.redeemed_points) redeemed_points," +
                "s.student_name,s.head_portrait from student s left join " +
                "student_exchange_details sed on(s.id=sed.student_id) where s.id = ? ";
        //学生的兑换详情
        Map<String,Object> map = null;
        try {
            map = studentExchangeDetailsJdbc.queryMap(sql,studentId);
        }catch (Exception e){
            map = new HashMap<>();
            map.put("fraction",0);
            map.put("student_id",studentId);
            map.put("prize_number",0);
            map.put("redeemed_points",0);
            map.put("student_name","");
            map.put("head_portrait","");
        }

        return new Result(map);
    }

    @Override
    public Result addStudentExchangeDetails(String deviceid, String studentId, String prizeId, String studentName) {
        logger.info("学生兑换奖品");
        Map<String, Object> stringObjectMap4 = studentExchangeDetailsJdbc.queryDevice(deviceid);
        //查询兑换奖品信息
        Prize p = prizeRepository.findById(Integer.valueOf(prizeId)).get();
        //判断如果为0则不可购买
        if(p.getStock()==0){
            return  new Result(CodeUtil.THE_QUOTA_IS_FULL);
        }

        synchronized(this){
            //查询
            StudentExchangeDetails sed =  studentExchangeDetailsRepository.findByStudentId(Integer.valueOf(studentId));
            //如果为空
            if(sed == null){
                logger.info("此学生无分数");
                return  new Result(CodeUtil.INSUFFICIENT_SCORE);
            }else if(sed.getFraction()<p.getPointsRequired()){
                logger.info("分数不足");
                return  new Result(CodeUtil.INSUFFICIENT_SCORE);
            }

            //创建兑换记录
            StudentExchangeRecord ser =  new StudentExchangeRecord();
            ser.setAddTime(new Date());
            ser.setClassId(Integer.valueOf(stringObjectMap4.get("classid").toString()));
            ser.setPrizeId(p.getId());
            ser.setState(0);
            ser.setStudentId(Integer.valueOf(studentId));
            ser.setStudentName(studentName);
            //未查看
            ser.setWhether(0);

            //扣除学生分数
            sed.setFraction(sed.getFraction()-p.getPointsRequired());
            //已兑换分数增加
            sed.setRedeemedPoints(sed.getRedeemedPoints()+p.getPointsRequired());
            //兑换个数增加
            sed.setPrizeNumber(sed.getPrizeNumber()+1);
            //库存减一
            p.setStock(p.getStock()-1);


            studentExchangeDetailsRepository.save(sed);
            studentExchangeRecordRepository.save(ser);
            prizeRepository.save(p);
        }

        return  new Result();
    }

    @Override
    public Result findPrizeList(String deviceid) {
        logger.info("查询奖品列表");
        Map<String, Object> stringObjectMap4 = studentExchangeDetailsJdbc.queryDevice(deviceid);
        //查询可兑换奖品
        String sql = "select p.id,p.prize_name,p.prize_description,p.teacher_id,p.points_required ,p.stock,p.url," +
                "p.school_id,t.`name` teacherName from  prize_class pc " +
                "left join prize p on(p.id=pc.prize_id) " +
                "inner join teacher t on(t.id=p.teacher_id) where pc.class_id = ? and del = 0 GROUP BY p.id desc";
        List<Map<String,Object>> prizeList = studentExchangeDetailsJdbc.queryListMap(sql,stringObjectMap4.get("classid"));

        return new Result(prizeList);
    }

    @Override
    public Result findRecordList(String deviceid, String studentId) {
        logger.info("查询兑换记录");
        Map<String, Object> stringObjectMap4 = studentExchangeDetailsJdbc.queryDevice(deviceid);

        //查询学生兑换记录
        String sql = "select ser.id,ser.student_name,ser.prize_id,ser.state,ser.class_id," +
                "DATE_FORMAT(ser.add_time,'%Y-%m-%d %T')add_time,t.`name` teacherName ," +
                "p.points_required,p.prize_name ,p.prize_description,p.url from " +
                "student_exchange_record ser inner join prize p on (p.id=ser.prize_id) " +
                "inner join teacher t on(t.id=p.teacher_id) WHERE ser.student_id = ? GROUP BY ser.id desc";
        List<Map<String,Object>> recordList = studentExchangeDetailsJdbc.queryListMap(sql,studentId);
        return new Result(recordList);
    }
}
